<template>
  <div>
    <div>
      <div class="address-top">
        <p @click="back">返回</p>
        <p>申请通知</p>
        <p class="no-content"></p>
      </div>
      <!-- 好友申请 -->
      <p v-show="lists.length" class="apply-title padd15">好友申请</p>
      <div class="flex apply-list padd15 white" v-for="(val,key) in lists" :key="key">
        <img class="img" :onerror="defaultImg" :src="val.Image?val.Image:c2cHead">
        <div class="flex1 flex right-mes">
          <p class="name">
            <i class="name_i">{{val.Nick?val.Nick:val.To_Account}}</i>(<span>{{val.To_Account}}</span>)
          </p>
          <p class="apply" @click="showMask(val,'friend')">查看申请</p>
        </div>
      </div>
      <!-- 群申请 -->
      <p v-show="msgArr.length" class="apply-title padd15">群申请</p>
      <div class="flex apply-list padd15 white" v-show="msgArr.length > 0" v-for="(val,key) in msgArr" :key="key">
        <!--&lt;!&ndash;  <img v-show="val.Tag_Profile_IM_Image" class="img" :src=val.Tag_Profile_IM_Image alt="">-->
        <img class="img" :onerror="defGroupImg">
        <div class="flex1 flex right-mes">
          <p class="name">
            <i class="name_i">{{val.GroupName?val.GroupName:''}}</i>(<span>{{val.GroupId?val.GroupId:0}}</span>)
          </p>
          <p class="apply" @click="showMask(val,'group')">查看申请</p>
        </div>
      </div>
      <!-- 一刷新就没有通知了 -->
      <!-- 通知 -->
      <p v-show="systemArr.length||applyResult.length" class="apply-title padd15">通知</p>

      <!--好友申请结果通知-->
      <div class="flex apply-list padd15 white" v-for="item in applyResult" v-if="applyResult&&item.Accounts" >
        <img class="img" :onerror="defaultImg" :src="item.image?item.image:c2cHead">
        <div class="flex1 flex right-mes">
          <p class="name">
            <i class="name_i">{{item.nick}}</i>(<span>{{item.Accounts[0]}}</span>)
          </p>
          <p>{{item.msg}}</p>
        </div>
      </div>

      <!-- 群组系统消息 -->
      <div class="flex apply-list padd15 white" v-for="item in systemArr">
        <img class="img" :onerror="defGroupImg" src="" alt="">
        <div class="flex1 flex right-mes">
          <p class="name">
            <i class="name_i">{{item.GroupName}}</i>(<span>{{item.GroupId}}</span>)
          </p>
          <p>{{item.myInfo}}</p>
        </div>
      </div>

      <!-- 没有申请-->
      <div v-show="noApply && noGroupApply" class="flex-center" style="height: .5rem;">
        暂时没有相关申请
      </div>
    </div>
    <!-- mask -->
    <div class="mask" v-show="mask">
      <div class="list">
        <div class="otherMes" v-show="friendMes">
          <p class="title">附言</p>
          <p class="content">{{friendMes}}</p>
        </div>
        <ul>
          <li v-for="(val,key) in applyList" :key="key" @click="select(val,key)">{{val}}</li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
  import {checkStatus} from '../../assets/js/login';
  import Client from '../../assets/js/common';
  import Chat from '../../assets/js/chat';
  import c2cHead from '../../assets/img/my@3x.png';
  export default {
    data () {
      return {
        defGroupImg: Client.defaultGroupImg,
        defaultImg: Client.defaultImg,
        mask: false, // 遮罩
        lists: [],
        groupLists: [],
        applyList: ['通过', '拒绝', '取消'],
        groupMes: null, // 群附言
        friendMes: '',
        toAccount: '',
        loginInfo: {},
        PendencyItem: null,
        noApply: false,
        noGroupApply: false,
        type: '', // friend group
        groupArr: {},
        agreeMes: '',  // 加群被同意
        refuseMes: '',  // 加群被拒绝
        kickMes: '',  // 群被踢
        destoryMes: '',  // 解散群
        createMes: '',  // 创建群
        inviteMes: '',  // 邀请加群
        quitMes: '',  // 主动退群
        adminMes: '',  // 被设置为管理员
        cancelAdminMes: '',  // 被取消管理员
        revokeMes: '',  // 群被回收
        msgArr: [], // 申请加群信息ID
        applyResult:[], //好友申请结果通知
        systemArr: [], // 群系统消息
        c2cHead,
        defaultImg:Client.defaultImg
      }
    },
    mounted () {
      checkStatus((loginInfo) => {
        this.getPendency(); // 好友申请列表
        this.pendencyGroupList();// 群申请列表
        this.pendencyGroupListRead();
        this.loginInfo = loginInfo;
        //console.log(loginInfo);
      });
    },
    methods: {
      // 返回
      back(){
        this.loginInfo.onPendencyAddNotify = null;
        history.back();
      },
      listenEvent(val, info) {
        for(let attr in val) {
          val[attr]["myInfo"] = info;
          this.systemArr.push(val[attr]);
        }
      },
      notifyResult(objs){
        switch(objs.Type){
          case 1:
            objs.msg = '已通过申请';
            break;
          case 4:
            objs.msg = '拒绝';
            break;
        }
        
        if(objs&&objs.Accounts){
          Chat.getProfilePortrait(objs.Accounts).then(resp=>{
             //console.log('ID回来的好友数据',resp);
             objs.image = resp[0].Image;
             objs.nick = resp[0].Nick;
             this.applyResult.unshift(objs);
          }).catch(err=>{
             this.applyResult.unshift(objs);
          });
        }
      },
      //读取好友申请列表
      getPendency() {
        let options = {
          'From_Account': this.loginInfo.identifier,
          'PendencyType': 'Pendency_Type_ComeIn',
          'StartTime': 0,
          'MaxLimited': 100,
          'LastSequence': 0,
          TagList: [
            "Tag_Profile_IM_Nick",
            "Tag_Profile_IM_SelfSignature", //个性签名
            "Tag_Profile_IM_Image", //头像
            "Tag_Profile_IM_Gender", //性别
            "Tag_Profile_IM_AllowType", //加好友验证方式
            "Tag_Profile_IM_Location", //所在地
            "Tag_Profile_IM_BirthDay", //生日
            "Tag_Profile_IM_MsgSettings" //消息设置 置0表示接收消息，置1则不接收消息
          ]

        };
        webim.getPendency(
          options,
          resp => {
            if (resp.UnreadPendencyCount > 0) {
              console.log('临时数据',resp);
              let arr = [],addWord = [];
              resp.PendencyItem.forEach((val,i)=>{
                if(val.AddWording){
                  addWord.push({id:val.To_Account,AddWording:val.AddWording});
                }
                arr.push(val.To_Account);
              });
              Chat.getProfilePortrait(arr).then(resp=>{
                resp.forEach((item,index)=>{
                  let mainItem = addWord.find((val,j)=>{
                    if(val.id == item.To_Account){
                      item.AddWording = val.AddWording;
                    }
                  });
                });
                this.lists = resp;
                this.noApply = this.lists.length ? false : true;
              }).catch(err=>{
                Client.errInfo();
                console.log('err',err);
              });
            } else {
              this.noApply = true;
            }
          },
          err => {
            console.log(err.ErrorInfo);
          }
        );
      },
      getMsgNotify(){
        let That = this;
        webim.syncMsgs(
          resp => {
            That.getApplyJoin();
          },
          err => {
            Client.errInfo();
            //alert(err.ErrorInfo);
          }
        );
      },
      getApplyJoin() {
        this.msgArr = this.loginInfo.onApplyJoinGroupRequestNotify;
        // console.log("bbbaa",  this.msgArr);
        // return;
        // this.msgArr = [];
        // this.applyJoinList = this.loginInfo.onApplyJoinGroupRequestNotify;
        // console.log("数据1", this.applyJoinList);
        // console.log("数据2", this.groupLists);
        // let obj = null;

        
        // for (let attr in this.applyJoinList) {
        //   let personId = this.applyJoinList[attr].Operator_Account;
        //   let groupId = this.applyJoinList[attr].GroupId;
        //   for (let key in this.groupLists) {
        //     let psonid = this.groupLists[key].From_Account;
        //     let Gid = this.groupLists[key].GroupId;
        //     // console.log(personId+" : "+psonid+" || "+ groupId+" : "+ Gid);
        //     if (psonid == personId && groupId == Gid) {
        //       obj = this.groupLists[key];
        //       obj["MsgSeq"] = this.applyJoinList[attr].MsgSeq;
        //       obj["MsgRandom"] = this.applyJoinList[attr].MsgRandom;
        //       obj["MsgKey"] = this.applyJoinList[attr].MsgKey;
        //       obj["Authentication"] = this.applyJoinList[attr].Authentication;
        //       this.msgArr.push(obj);
        //     }
        //   }
        // };

      },

      //处理好友申请
      responseFriend(To_Account, action) {
        let response_friend_item = [
          {
            'To_Account': To_Account,
            "ResponseAction": action
            //类型：Response_Action_Agree - 同意对方加自己为好友；
            //	   Response_Action_AgreeAndAdd - 同意并添加对方为好友；
            //	   Response_Action_Reject - 拒绝对方添加自己为好友。
          }
        ];
        let options = {
          'From_Account': this.loginInfo.identifier,
          'ResponseFriendItem': response_friend_item
        };
        webim.responseFriend(
          options,
          resp => {
            this.deleteTable(To_Account);
          },
          err => {
            Client.errInfo();
            console.log(err.ErrorInfo);
          }
        );
      },
      //删除好友申请
      deletePendency(del_account) {
        var options = {
          'From_Account': this.loginInfo.identifier,
          'PendencyType': 'Pendency_Type_ComeIn',
          'To_Account': [del_account]
        };
        webim.deletePendency(
          options,
          resp => {
            this.deleteTable(del_account);
          },
          err => {
            Client.errInfo();
            console.log(err.ErrorInfo);
          }
        );
      },
      //删除视图对应好友列表
      deleteTable(del_account){
        this.lists.forEach((ele, i) => {
          if (ele.To_Account == del_account) {
            this.lists.splice(i, 1);
          }
        });
      },
      // 显示遮罩
      showMask (val, type) {
        this.mask = true;
        this.type = type // 类型
        if (type === 'friend') {
          // 好友
          this.toAccount = val.To_Account;
          this.friendMes = val.AddWording;  // 附言
        } else if (type === 'group') {
          // 群
          this.groupMes = val.RemarkInfo   // 附言
          let obj = {
            GroupId: val.GroupId,
            From_Account: val.Operator_Account,
            Authentication: val.Authentication,
            ApplyInviteMsg: val.RemarkInfo,
            AddTime: 0,
            MsgKey: val.MsgKey,
            MsgRandom: val.MsgRandom,
            MsgSeq: val.MsgSeq
          }
          this.groupArr = obj;
          console.log("260", this.groupArr);

        }
      },
      // 选择遮罩
      select (val, key) {
        this.mask = false
        // 好友
        if (this.type == 'friend') {
          if (key == 0) {
            // 接受
            this.responseFriend(this.toAccount, 'Response_Action_AgreeAndAdd')
          } else if (key == 1) {
            // 拒绝
            this.responseFriend(this.toAccount, 'Response_Action_Reject')
          } else if (key == 2) {
            // 取消（就是删除好友请求）
            //this.deletePendency(this.toAccount)
          }
        } else if (this.type == 'group') {
          // 群
          switch (key) {
            case 0:
              console.log('ok'); // 接受
              this.handleApplyJoinGroupPendency('Agree')
              break;
            case 1:
              console.log('ok2'); // 拒绝
              this.handleApplyJoinGroupPendency('Reject')
              break;
            case 2:
              console.log('ok3'); // 取消
              break;
          }
        }
        //history.back()
      },
      // 初始化申请加群列表
      pendencyGroupList() {
        let That = this;
        webim.getPendencyGroup({
          'StartTime': 0,//开始时间
          'Limit': 100 //一次最多获取十条
        }, function (resp) {
          if (resp.PendencyList) {
            /* for (let i = 0; i < resp.PendencyList.length; i++) {
             That.group.ApplyJoinGroup.push(resp.PendencyList[i])
             }*/
            That.groupLists = resp.PendencyList;
            That.getMsgNotify();
          } else {
            That.noGroupApply = true
          }
        })
      },
      //处理加群申请
      handleApplyJoinGroupPendency(type) {
        let That = this;
        var options = {
          'GroupId': That.groupArr.GroupId, //群id
          'Applicant_Account': That.groupArr.From_Account, //申请人id
          'HandleMsg': type, //Agree-同意 Reject-拒绝
          'Authentication': That.groupArr.Authentication, //申请凭证
          'ApprovalMsg': That.groupArr.ApplyInviteMsg, //处理附言
          'UserDefinedField': "",//用户自定义字段
          'MsgKey': That.groupArr.MsgKey
        };
        //要删除的群未决消息
        let delApplyJoinGroupPendencys = {
          'DelMsgList': [
            {
              "From_Account": That.groupArr.From_Account,
              "MsgSeq": parseInt(That.groupArr.MsgSeq),
              "MsgRandom": parseInt(That.groupArr.MsgRandom)
            }
          ]
        };
        webim.handleApplyJoinGroupPendency(
          options,
          function (resp) {
            if (type == "Agree") {
              console.log("审核成功", resp);
            } else if (type == "Reject") {
              console.log("拒绝成功", resp);
            }
            //删除已处理的加群未决消息，否则下次登录的时候会重复收到加群未决消息
            That.deleteApplyJoinGroupPendency(delApplyJoinGroupPendencys);
          },
          function (err) {
            Client.errInfo();
            if (type == "Agree") {
              console.log("审核失败", err);
            } else if (type == "Reject") {
              console.log("拒绝失败", err);
            }
          }
        );
      },
      pendencyGroupListRead() {
        webim.getPendencyGroupRead({
              'ReportTime': 0,//处理时间
              'From_Account': this.loginInfo.identifier //当前登录用户
          }, function(resp) {
            
        })
      },
      //删除已处理的加群未决消息
      deleteApplyJoinGroupPendency(opts) {
        let That = this;
        webim.deleteApplyJoinGroupPendency(opts,
          function (resp) {
            console.log("删除已处理的加群请求", resp);
            let newArr = [];
            let notify = That.loginInfo.onApplyJoinGroupRequestNotify;
           
            for(let i = 0; i < notify.length; i++) {
              if(notify[i].Operator_Account == That.groupArr.From_Account && notify[i].GroupId == That.groupArr.GroupId){
                 // delete notify[attr];
                 notify.splice(i,1);
                
              }
            }
            for(let attr in That.msgArr){
              if(That.msgArr[attr].MsgSeq != That.groupArr.MsgSeq) {
                newArr.push(That.msgArr[attr]);
              }
            }
            That.msgArr = newArr;
//            That.$router.push({path:'/groupList'});
          },
          function (err) {
            Client.errInfo();
            console.log("删除失败", err.ErrorInfo);
          }
        );
      }
    },
    watch: {
      // 监听 申请加群被同意 系统消息
      "loginInfo.onApplyJoinGroupAcceptNotify": function (val, oldval) {
        this.listenEvent(val, "加群成功");
      },
      // 被同意和被踢消息出现后，报错，duplicate key detected '0'
      // 监听 申请被拒绝 系统消息
      "loginInfo.onApplyJoinGroupRefuseNotify": function (val, oldval) {
        this.listenEvent(val, "申请被拒绝");
      },
      // 监听 申请被踢 系统消息
      "loginInfo.onKickedGroupNotify": function (val, oldval) {
        this.listenEvent(val, "被管理踢出");
      },
      // 监听 解散群 系统消息
      "loginInfo.onDestoryGroupNotify": function (val, oldval) {
       this.listenEvent(val, "群组被解散");
      },
      // 监听 创建群 系统消息
      "loginInfo.onCreateGroupNotify": function (val, oldval) {
        this.listenEvent(val, "创建群");
      },
      // 监听 被邀请加群 系统消息
      "loginInfo.onInvitedJoinGroupNotify": function (val, oldval) {
        this.listenEvent(val, "被邀请加群");
      },
      // 监听 主动退群 系统消息
      "loginInfo.onQuitGroupNotify": function (val, oldval) {
        this.listenEvent(val, "主动退群");
      },
      // 监听 被设置为管理员 系统消息
      "loginInfo.onSetedGroupAdminNotify": function (val, oldval) {
        this.listenEvent(val, "被设管理员");
      },
      // 监听 被取消管理员 系统消息
      "loginInfo.onCanceledGroupAdminNotify": function (val, oldval) {
        this.listenEvent(val, "取消管理员");
      },
      // 监听 群被回收 系统消息
      "loginInfo.onRevokeGroupNotify": function (val, oldval) {
        this.listenEvent(val, "群组被回收");
      },
      "loginInfo.onApplyJoinGroupRequestNotify": function (val, oldval) {
        this.msgArr = val;
      },
      // 好友申请监听
      "loginInfo.onPendencyAddNotify": function(val) {
        //console.log('好友申请',val);
        if (val && val.PendencyList) {
          val.PendencyList.forEach((item,i)=>{
             let hasObj = false;
             if(this.lists.length>0){
               //console.log('this.lists',this.lists)
               this.lists.forEach((obj)=>{
                 if(obj.To_Account == item.PendencyAdd_Account){
                   hasObj = true;
                   return;
                 }
               })
             }
             if(!hasObj){
               item.To_Account = item.PendencyAdd_Account;
               if(item.ProfileImNick){
                  item.Nick = item.ProfileImNick;
               }
               this.lists.unshift(item);
             }
          });
        }
      },
      "loginInfo.onFriendAddNotify":function(val){
        this.notifyResult(val);
        console.log('好友添加通知回调',val);
      },
      "loginInfo.onPendencyDeleteNotify":function(val){
        this.notifyResult(val);
        console.log('好友添加未决删除',val);
      }
    }
  }

</script>
<style lang="less" rel="stylesheet/less" scoped>
  .font16 {
    font-size: .16rem;
  }

  .color4a {
    color: #4A4A4A;
  }

  /* 好友申请 */
  .apply-title {
    line-height: .37rem;
    color: #818181;
  }

  /* 申请列表*/
  .apply-list {
    height: .6rem;
    display: flex;
    align-items: center!important;
    .img {
      width: .4rem;
      height: .4rem;
      border-radius: 50%;
      margin-right: .1rem;
    }
    .flex1 {
      display: flex;
      align-items: center;
    } 
    .right-mes {
      justify-content: space-between;
      border-bottom: .01rem solid #F1F1F1;
      line-height: .6rem;
      .name {
        display: flex;
        align-items: center;
        height: 0.4rem;
        .name_i,span{
          display: inline-block;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
        }
        .name_i {
          max-width: 0.8rem;
          font-style: normal;
          height: 0.4rem;
          line-height: 0.4rem;
        }
        .font16;
        .color4a;
        span {
          color: #66A1E6;
          max-width:1.2rem;
        }
      }
      .apply {
        color: #EC5656;
      }
    }
  }

  .mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
    background: rgba(0, 0, 0, .1);
    display: flex;
    align-items: center;
    .list {
      margin:0 auto;
      background: #fff;
      width: 2.35rem;
      ul {
        li {
          color: #000;
          text-align: center;
          line-height: .4rem;
          height: .4rem;
          border-bottom: .005rem solid #ccc;
          font-size: .14rem;
        }
      }
      .otherMes {
        padding:.1rem; 
        border-bottom: .005rem solid #ccc;
        p {
          line-height: 1.8;
        }
        .title {
          font-size: .14rem;
          color: #000;
        }
        .content{
          font-size: .12rem;
          color:#818181;
          max-height:.6rem;
          overflow-y: scroll;
        }
      }
    }
  }
</style>
